package com.kaggle.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
import org.apache.flink.api.java.tuple.Tuple2;

public class WordCount {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
       // env.setParallelism(5);
        String inputpath = "F:\\sourcecode\\flink\\src\\main\\resources\\name.txt";

        DataStreamSource<String> input = env.readTextFile(inputpath);
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = input.flatMap(new MyFlatMapper())
                .keyBy(0)
                .sum(1);
        result.print();
        env.execute();

    }

    public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String, Integer>>{
        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            String[] words = value.split(" ");
            for (String word : words) {
                out.collect(new Tuple2<>(word, 1));
            }
        }
    }
}
